package com.cxl.mapreduce._15topN;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.Iterator;
import java.util.TreeMap;

public class TopNMapper extends Mapper<LongWritable, Text, FlowBean, Text> {

    FlowBean k ;
    Text v = new Text();
    TreeMap<FlowBean, Text> flowMap = new TreeMap<>();

    @Override
    protected void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {
//		13736230513	2481	24681	27162

        // 1 获取一行
        String line = value.toString();

        // 2 切割
        String[] fields = line.split("\t");

        // 3 封装对象
        String phoneNum = fields[0];

        long upFlow = Long.parseLong(fields[1]);
        long downFlow = Long.parseLong(fields[2]);
        long sumFlow = Long.parseLong(fields[3]);
        k = new FlowBean();
        k.setDownFlow(downFlow);
        k.setUpFlow(upFlow);
        k.setSumFlow(sumFlow);

        v.set(phoneNum);
        flowMap.put(k,v);
        if (flowMap.size()>10){
            flowMap.remove(flowMap.lastKey());
        }
//		// 4 写出
//		context.write(k, v);
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        Iterator<FlowBean> iterator = flowMap.keySet().iterator();
        while (iterator.hasNext()){
            FlowBean k = iterator.next();
            context.write(k,flowMap.get(k));
        }
    }
}
